﻿using System;
using System.Linq.Expressions;

namespace FT.Architecture.Utils.Reflection
{
    public static class ExpressionsExtensions
    {
        public static Expression<Func<T, object>> GetLambdaExpressionFor<T>(this string sortColumn)
        {
            var type = typeof(T);
            var parameterExpression = Expression.Parameter(type, "x");
            Expression body = Expression.PropertyOrField(parameterExpression, sortColumn);

            if (!parameterExpression.IsByRef)
            {
                body = Expression.MakeUnary(ExpressionType.Convert, body, typeof(object));
            }

            var expression = Expression.Lambda<Func<T, object>>(body, new[] { parameterExpression });

            return expression;
        }
    }
}
